package model

import (
	"errors"
	"gorm.io/gorm"
	"time"
)

type (
	ProjectMemberModel interface {
		Insert(Member Project_Member) (err error)
		FindOne(Member Project_Member) (Project_Member, error)
		Update(Member Project_Member) (err error)
		DeleteSoft(Member Project_Member) (err error)
		Delete(Member Project_Member) (err error)
	}

	DefaultProjectMemberModel struct {
		conn  *gorm.DB
		table string
	}

	Project_Member struct {
		Project_id          int       `db:"project_id"  json:"project_id"`
		Project_Member_id   int       `db:"project_member_id"  json:"project_member_id"`
		Project_Member_name string    `db:"project_member_name"  json:"project_member_name"`
		Project_Member_Tel  string    `db:"project_member_tel"  json:"project_member_tel"`
		Create_time         time.Time `db:"create_time"  json:"create_time"`
		Delete_time         time.Time `db:"delete_time"  json:"delete_time"`
		DelState            int       `db:"del_state"  json:"del_state"`
		Role                string    `db:"role"  json:"role"`
	}
)

func NewDefaultProjectMemberModel(conn *gorm.DB) *DefaultProjectMemberModel {
	return &DefaultProjectMemberModel{
		conn:  conn,
		table: "project_member",
	}
}

func (mem *DefaultProjectMemberModel) Insert(member Project_Member) (err error) {
	member.Create_time = time.Now()
	member.Delete_time = time.Unix(0, 0)
	mem.conn.Create(&member)
	return err
}

func (mem *DefaultProjectMemberModel) FindOne(member Project_Member) (Project_Member, error) {
	var err error
	var count int64
	mem.conn.Model(&member).Where("project_member_id=?", member.Project_id).Count(&count)
	if count <= 0 {
		err = errors.New("数据不存在")
		return Project_Member{}, err
	}
	mem.conn.Where("person_id=?", member.Project_id).First(&member)

	return member, nil
}

func (mem *DefaultProjectMemberModel) Update(member Project_Member) (err error) {

	var count int64
	mem.conn.Model(&member).Where("project_member_id=?", member.Project_id).Count(&count)
	if count <= 0 {
		err = errors.New("数据不存在")
		return err
	}
	mem.conn.Model(&member).Where("project_member_id=?", member.Project_id).Updates(&member)
	return nil
}

func (mem *DefaultProjectMemberModel) DeleteSoft(member Project_Member) (err error) {
	member.Delete_time = time.Now()
	member.DelState = 1
	var count int64
	mem.conn.Model(&member).Where("project_member_id=?", member.Project_id).Count(&count)
	if count <= 0 {
		err = errors.New("数据不存在")
		return err
	}
	err = mem.Update(member)
	if err != nil {
		return err
	}
	return nil
}

func (mem *DefaultProjectMemberModel) Delete(member Project_Member) (err error) {
	var count int64
	mem.conn.Model(&member).Where("project_member_id=?", member.Project_id).Count(&count)
	if count <= 0 {
		err = errors.New("数据不存在")
		return err
	}
	mem.conn.Model(&member).Where("project_member_id=?", member.Project_id).Delete(&member)
	return nil
}
